﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using Commonlib;

namespace AlbonWeb.Manager.OrderManager
{
    public partial class OrderList : System.Web.UI.Page
    {
        private readonly BLL.OrderBLL orderbll = new BLL.OrderBLL();
        private readonly BLL.UserBLL userbll = new BLL.UserBLL();
        private readonly BLL.OrderItemBLL orderitembll = new BLL.OrderItemBLL();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //绑定OrderClass
                bindClass();
                ViewState["limit"] = "where active=1";
               
                //Manager组内的OrderManager  传递一个showall=1的参数，显示所有的订单
                //如果找不到该参数，则只显示当前登录用户的订单
                if (Request["showall"] == null)
                {
                    ViewState["showall"] =false;
                    userName.Text = User.Identity.Name;
                    userName.Enabled = false;
                }
                else
                {
                    ViewState["showall"] = true;
                }
                bindRep();
            }
            
        }

        protected void bindClass()
        {
            string cmdstr = "select * from OrderClass";
            SqlHelper.BindDropDownList(ddlOrderClass, "className", "ID", SqlHelper.SqlConnectionString, CommandType.Text, cmdstr, null);
            ddlOrderClass.Items.Insert(0, new ListItem("--Order Class--", "0"));
        }
        //绑定订单数据
        protected void bindRep()
        {
            ViewState["limit"] += " and finished=1";
            if (ddlOrderClass.SelectedIndex != 0)
            {
                ViewState["limit"] += " and classID="+ddlOrderClass.SelectedValue;
            }
            if (userName.Text.Trim() != "")
            {
                ViewState["limit"] += " and userName like '%"+userName.Text.Trim()+"%'";
            }
            if (refNo.Text.Trim() != "")
            {
                ViewState["limit"] += " and refNo like '%" + refNo.Text.Trim() + "%'";
            }
            if (startDate.Text != "")
            {
                ViewState["limit"] += " and createDate>'" + startDate.Text + "'";
            }
            if (endDate.Text != "")
            {
                ViewState["limit"] += " and createDate<'" + endDate.Text + "'";
            }
            AspNetPager1.Visible = true;
            string cmdstr = "select count(*) from OrderInfoView "+ViewState["limit"].ToString();
            AspNetPager1.RecordCount =int.Parse(SqlHelper.ExecuteScalar(SqlHelper.SqlConnectionString, CommandType.Text, cmdstr, null).ToString());
            SqlParameter[] parameters = new SqlParameter[]{
                new SqlParameter("@tablename","OrderInfoView"),
                new SqlParameter("@startIndex",AspNetPager1.StartRecordIndex),
                new  SqlParameter("@endIndex",AspNetPager1.EndRecordIndex),
                new SqlParameter("@limit",ViewState["limit"].ToString()),
                new SqlParameter("@orderby","createDate desc")
            };
            SqlHelper.BindRepeater(repOrder, SqlHelper.SqlConnectionString, CommandType.StoredProcedure, "netpager", parameters);
        }

        //换页
        protected void AspNetPager1_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e)
        {
            AspNetPager1.CurrentPageIndex = e.NewPageIndex;
            bindRep();
        }


        protected void repOrder_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemIndex != -1)
            {
                string orderid = ((HiddenField)e.Item.FindControl("hforderid")).Value;
                //显示itemList
                //Label itemList = (Label)e.Item.FindControl("itemList");
                //itemList.ToolTip = orderbll.getItemsDescribe(orderid);
                DataTable dt = orderbll.getOrderByID(orderid);
                //显示OrderStatus（倒计时，buyMe或者订单类别）
                LinkButton lbStatus = (LinkButton)e.Item.FindControl("orderStatus");
                switch (orderbll.orderStatus(orderid))
                {
                    case "unProcessed":
                        {
                            lbStatus.Text = showTime(DateTime.Parse(dt.Rows[0]["createDate"].ToString()));
                            lbStatus.CommandName = "unProcessed";
                            lbStatus.OnClientClick = "return confirm('Put it in work NOW?')";
                            break;
                        }

                    case "BuyMe":
                        {
                            lbStatus.Text = "<img src='/images/buyme.jpg' alt='' />";
                            lbStatus.CommandName = "BuyMe";
                            break;
                        }
                    default:
                        {
                            lbStatus.Text = dt.Rows[0]["className"].ToString();
                            lbStatus.OnClientClick = "return openDialog('/Manager/OrderManager/ChangeClass.aspx?orderid=" + lbStatus.CommandArgument + "',400,200,200)";
                            lbStatus.Font.Underline = false;
                            lbStatus.ForeColor = System.Drawing.Color.Black;
                            lbStatus.Font.Bold = true;
                            break;
                        }
                }
                //控制订单是否可以被删除和修改（超过三天和已经提交的不可删除）
                ImageButton imgDelete = (ImageButton)e.Item.FindControl("imgDelete");
                ImageButton imgEdit = (ImageButton)e.Item.FindControl("imgEdit");
                if (userbll.isDealer)
                {
                    if (orderbll.isProcessed(orderid))
                    {
                        imgDelete.Visible = false;
                        imgEdit.Enabled = false;
                        imgEdit.ImageUrl = "/images/grv_edit_gray.gif";
                    }
                }
                //显示信息状态（Message）
                Image imgMessage = (Image)e.Item.FindControl("imgMessage");
                BLL.MessageBLL messagebll = new BLL.MessageBLL();
                if (messagebll.hasNewMessage(orderid,User.Identity.Name))
                {
                    imgMessage.ImageUrl = "/images/email_new.gif";
                }
                else if (messagebll.hasUnRead(orderid, User.Identity.Name))
                {
                    imgMessage.ImageUrl = "/images/email_unread.gif";
                }
                //显示invoice状态
                BLL.InvoiceBLL invoicebll = new BLL.InvoiceBLL();
                string invoiceNo=((HiddenField)e.Item.FindControl("hfinvoiceNo")).Value;
                ImageButton invoiceShow = (ImageButton)e.Item.FindControl("invoiceShow");
                DataTable dtInvoice = invoicebll.getInvoiceByNo(invoiceNo);
                if (dtInvoice.Rows.Count >0)
                {
                    invoiceShow.OnClientClick = "return openDialog('"+dtInvoice.Rows[0]["invoicePath"].ToString()+"')";
                }
                Image invoiceEdit = (Image)e.Item.FindControl("invoiceEdit");
                if(!userbll.isAccountant)
                {
                    invoiceEdit.Visible = false;
                }
                switch (invoicebll.getStatus(invoiceNo))
                {
                    
                    case "totaled":
                        invoiceShow.ImageUrl = "/images/totaledbill.gif";
                        
                        break;
                    case "changed":
                        invoiceShow.ImageUrl = "/images/changedbill.jpg";
                        break;
                    case "finished":
                        invoiceShow.ImageUrl = "/images/finished_bill.gif";
                        invoiceEdit.Visible = false;
                        break;
                    case "no":
                        invoiceShow.Visible = false;
                        invoiceEdit.Visible = false;
                        break;
                    default:
                        invoiceShow.ImageUrl = "/images/unreadbill.gif";
                        invoiceShow.Enabled = false;
                        break;
                } 
                //显示发货的截止日期，准时用绿色表示，过时用红色显示
                Label shipdate = (Label)e.Item.FindControl("shipDate");
                if (shipdate.Text != "")
                {
                    DateTime date = DateTime.Parse(shipdate.Text);
                    shipdate.Text = date.ToString("dd-MM-yyyy");
                    if (orderbll.isDelay(orderid,date))
                    {
                        shipdate.ForeColor = System.Drawing.Color.Red;
                    }
                }
                //发货状态（飞机）
                ImageButton shipMent = (ImageButton)e.Item.FindControl("shipMent");
                ImageButton addShip = (ImageButton)e.Item.FindControl("addShip");
                shipMent.CommandArgument = orderid;
                addShip.CommandArgument = orderid;
                //已完成发货的订单
                if (orderbll.finishShip(orderid))
                {
                    addShip.Visible = false;
                    shipMent.ImageUrl = "/images/ship_finish.gif";
                    shipMent.CommandName = "Finish";
                }
                //未完成发货的订单
                else
                {
                    //可以发货的订单（完成生产）
                    if (orderbll.finishProduce(orderid)&&!userbll.isDealer)
                    {
                        addShip.Visible = true;
                        BLL.ShipBLL shipbll = new BLL.ShipBLL();
                        shipMent.CommandName = "Wait";
                        //已经添加到发货车中的订单隐藏添加按钮
                        ArrayList shipcart = (ArrayList)Session["shipcart"];
                        if (shipcart.Contains(orderid))
                        {
                            addShip.Visible = false;
                        }
                    }
                    //不可以发货的订单
                    else
                    {
                        shipMent.Enabled = false;
                        addShip.Visible = false;
                    }
                }
                //绑定订单项
                Repeater repItem = (Repeater)e.Item.FindControl("repItem");
                string cmdstr = "select * from OrderItemView where finished=1 and orderID=" + orderid;
                SqlHelper.BindRepeater(repItem, SqlHelper.SqlConnectionString, CommandType.Text, cmdstr, null);
            }
           
        }
        protected void shipMent_Click(object sender, ImageClickEventArgs e)
        {
            ImageButton ibtn = (ImageButton)sender;
            if (ibtn.CommandName == "Finish")
            {
                Response.Redirect("/Manager/OrderManager/ShipRecord.aspx?orderid="+ibtn.CommandArgument);
            }
            else if (ibtn.CommandName == "Wait")
            {
                Response.Redirect("/Manager/OrderManager/ShipMent.aspx?orderid="+ibtn.CommandArgument);    
            }
        }
        protected void addShip_Click(object sender, ImageClickEventArgs e)
        { 
            ImageButton ibtn=(ImageButton)sender;
            ((ArrayList)Session["shipcart"]).Add(ibtn.CommandArgument);
            ibtn.Visible = false;
        }
        //计算时间差
        protected string showTime(DateTime createDate)
        {
            TimeSpan ts = createDate.AddDays(3) -DateTime.Now;
            return ts.Days + "day" + ts.Hours + ":" + ts.Minutes + ":" + ts.Seconds;
        }
        //修改订单状态 
        protected void orderStatus_Click(object sender, EventArgs e)
        {
            LinkButton lbStatus = (LinkButton)sender;
            if (lbStatus.CommandName == "unProcessed")
            {
                orderbll.pocessOrder(lbStatus.CommandArgument);
                bindRep();
            }
            else if (lbStatus.CommandName == "BuyMe")
            {
                Response.Redirect("/Manager/OrderManager/ClothList.aspx?orderidlist=" + lbStatus.CommandArgument);
            }
            else
            {
                
            }

        }
        //查询
        protected void btnSearch_Click(object sender, ImageClickEventArgs e)
        {
            ViewState["limit"] = "where active=1";
            bindRep();
        }
        //选择类别后自动查询
        protected void ddlOrderClass_SelectedIndexChanged(object sender, EventArgs e)
        {
            ViewState["limit"] = "where active=1";
            bindRep();
        }
        //查找需要购买布料的订单（BuyMe）不用原来的分页绑定
        protected void buyMe_Click(object sender, ImageClickEventArgs e)
        {
            AspNetPager1.Visible = false;
            repOrder.DataSource= orderbll.getBuyMeOrder(userName.Text.Trim());
            repOrder.DataBind();
        }

        //查询未读信息
        protected void unReadEmail_Click(object sender, ImageClickEventArgs e)
        {
            AspNetPager1.Visible = false;
            repOrder.DataSource = orderbll.getOrderWithUnReadMessage(User.Identity.Name,bool.Parse(ViewState["showall"].ToString()));
            repOrder.DataBind();
        }
        //查询新信息
        protected void newMessage_Click(object sender, ImageClickEventArgs e)
        {
            AspNetPager1.Visible = false;
            repOrder.DataSource = orderbll.getOrderWithNewMessage(User.Identity.Name,bool.Parse(ViewState["showall"].ToString()));
            repOrder.DataBind();
        }

        //删除订单
        protected void imgDelete_Click(object sender, ImageClickEventArgs e)
        {
            string orderid = ((ImageButton)sender).CommandName.ToString();
            if (orderbll.moveToRecycleBin(orderid))
            {
                bindRep();    
            }
        }
        //修改订单
        protected void imgEdit_Click(object sender, ImageClickEventArgs e)
        {
            string orderid = ((ImageButton)sender).CommandName.ToString();
            Response.Redirect("/Order/orderItemList.aspx?orderid="+orderid);
        }

    }
}